package com.hui.java.concurrency;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * TODO: 遇见异常时，ThreadPoolExecutor是如何捕获异常的
 *
 * @author chenth
 * @create 2019-04-17 20:25
 **/
public class ThreadPoolExecutorExceptionQuestion {

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                1,
                1,
                0,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>()

        ){
            /**
             * 通过覆盖{@link ThreadPoolExecutor#afterExecute(Runnable, Throwable)}达到获取异常的信息
             * @param r
             * @param t
             */
            @Override
            protected void afterExecute(Runnable r,Throwable t){
                System.out.printf("线程[%s] 遇到了异常，详细信息： %s \n",
                        Thread.currentThread().getName(),
                        t.getMessage());
            }
        };
        executor.execute(() -> {
            throw new RuntimeException("数据达到阈值");
        });

        //等待两秒钟，确保提交的任务已经完成
        executor.awaitTermination(2,TimeUnit.SECONDS);
        //关闭线程池
        executor.shutdown();
    }
}
